package com.zyc.studentstudy.ui.youdao

import android.annotation.SuppressLint
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.lifecycle.lifecycleScope
import com.zyc.studentstudy.databinding.FragmentCidianBinding
import com.zyc.studentstudy.simple.SimpleFragment
import com.zyc.studentstudy.utils.InputMethodUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * Created by zhangyuncai on 2025/10/14.
 * 描述：有道词典
 */
class CidianFragment : SimpleFragment() {
    private val H5_JSCALL_NAME = "Android"
    private lateinit var mDB: FragmentCidianBinding
    private var httpUrl = "https://m.youdao.com/dict"
    private val mWebView: WebView by lazy {
        mDB.webCidian
    }

    override fun useDatabing(inflater: LayoutInflater, container: ViewGroup?): View? {
        mDB = FragmentCidianBinding.inflate(inflater, container, false)
        return mDB.root
    }

    override fun lazyFetchData() {
    }

    override fun initView() {
        val jsCall = object : JsCall() {
            override fun callbackParam(param: String?) {

            }

        }
        mWebView.apply {
            settings.javaScriptEnabled = true
            settings.mediaPlaybackRequiresUserGesture = false
            webViewClient = object : WebViewClient() {
                override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                    view.loadUrl(url)
                    return true
                }
            }
            getSettings().setJavaScriptEnabled(true)
            addJavascriptInterface(
                jsCall,
                H5_JSCALL_NAME
            )
            loadUrl(httpUrl)
            if (false) {
                return
            }
            delayTime(2000) {
                mWebView.evaluateJavascript(
                    """
        (function() {
            var style = document.createElement('style');
            style.innerHTML = `
                #top-download,
                .top-download,
                [class*="top-download"],
                [id*="top-download"] {
                    display: none !important;
                    visibility: hidden !important;
                    opacity: 0 !important;
                    height: 0 !important;
                    width: 0 !important;
                    position: absolute !important;
                    z-index: -9999 !important;
                }
            `;
            document.head.appendChild(style);
        })();
    """.trimIndent(), null
                )
                mWebView.evaluateJavascript(
                    """
        (function() {
            var style = document.createElement('style');
            style.innerHTML = `
                #product,
                .product,
                [class*="product"],
                [id*="product"] {
                    display: none !important;
                    visibility: hidden !important;
                    opacity: 0 !important;
                    height: 0 !important;
                    width: 0 !important;
                    position: absolute !important;
                    z-index: -9999 !important;
                }
            `;
            document.head.appendChild(style);
        })();
    """.trimIndent(), null
                )
            }
        }
    }

    ///点击语音按钮
    fun clickCidianYuyin() {
        viewLifecycleOwner.lifecycleScope.launch(Dispatchers.Main) {
            mWebView.evaluateJavascript(
                "javascript:document.querySelectorAll('.phonetic-speech')[1].click();",
                null
            )
        }
    }

    ///输入词典中的内容
    @SuppressLint("RestrictedApi")
    fun inputCidianText() {//translate_btn
        val key = "hello"
        mWebView.evaluateJavascript(
            """
    (function() {
        var input = document.querySelector('#search_input');
        var translate_btn = document.querySelector('.translate_btn');
        if (input) {
            // 1. 设置值
            input.value = '$key';
            
            // 2. 触发所有可能的事件
            var events = ['input', 'change', 'keyup', 'keydown', 'keypress', 'blur', 'focus'];
            events.forEach(function(eventType) {
                var event = new Event(eventType, { bubbles: true });
                input.dispatchEvent(event);
            });
            
        }
        if(translate_btn) {
            translate_btn.click();
        }
    })();
""".trimIndent(), null
        )
        delayTime(500) {
            val downEvent = KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER)
            val upEvent = KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER)

            mActivity.dispatchKeyEvent(downEvent)
            mActivity.dispatchKeyEvent(upEvent)
        }
        InputMethodUtil.closeKeyBoard(mActivity)
    }

    override fun initEvent() {
    }

}